package com.example.shardingjdbctest.algorithm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.stereotype.Component;

import java.util.Collection;
@Slf4j
@Component
public class MyDBPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Integer> {
    public MyDBPreciseShardingAlgorithm() {
    }

    @Override
    public String doSharding(Collection<String> databaseNames, PreciseShardingValue<Integer> shardingValue) {
        log.info("=======分库开始=========");
        for(String databaseName:databaseNames){
           String value =  shardingValue.getValue() % databaseNames.size() +1+ "";
           if(databaseName.endsWith(value)){
               log.info("当前库:"+databaseName);
               log.info("=======分库结束=========");
               return databaseName;
           }
        }

       throw new IllegalArgumentException();
    }
}
